<?php
/*
 * setup
 */

/*
if($_SERVER['REMOTE_ADDR']!='110.77.202.193'){
    include('close.php');
    exit();
}
*/

header("Access-Control-Allow-Methods: *");
header("Access-Control-Allow-Headers: *");
header("Cache-Control: no-cache, must-revalidate");

ob_end_clean();
header("Connection: Close");
ob_start();
//ignore_user_abort(true);

function __autoload($class)
{
	foreach(glob('class/*.class.php') as $key => $value){
		$file = pathinfo($value);
		if($file['basename'] == $class.'.class.php'){
			include_once $value;
			break;
		}
	}
	foreach(glob('class/*/*.class.php') as $key => $value){
		$file = pathinfo($value);
		if($file['basename'] == $class.'.class.php'){
			include_once $value;
			break;
		}
	}
	if (!class_exists($class, false)) {
		trigger_error("Not found class", E_USER_WARNING);
	}
}

set_error_handler(function($errno, $errstr, $errfile, $errline,$context) {
	Log::error($errstr);
	throw new Exception($errstr, $errno);
	return false;
}, E_ALL);

/*
 * run
 */

function printStart()
{
	if(!Helper::isAjax()) 
	{
		$page = empty($_GET['page']) ? 'home' : $_GET['page'];
		$pageArr = explode('/', $page);
		$first = strtolower($pageArr[0]);
		if($first=='accounting' || $first == 'technic' || $first == 'marketing'){
			require_once 'views/template/admin.start.view.php';
		}
		else {
			require_once 'start.template.php';
		}
	}
}

function printEnd()
{
	if(!Helper::isAjax()){
		$page = empty($_GET['page']) ? 'home' : $_GET['page'];
		$pageArr = explode('/', $page);
		$first = strtolower($pageArr[0]);
		if($first=='accounting' || $first == 'technic' || $first == 'marketing'){
			require_once 'views/template/admin.end.view.php';
		}
		else {
			require_once 'end.template.php';
		}
	}
}

try
{
	session_start();
	
	printStart();
	$page = empty($_GET['page']) ? 'home' : $_GET['page'];
	if(!@include('pages/'.$page.'.page.php')){
		echo <<<HTML
		<h1 class="page404"><center>404 Page not found</center></h1>
HTML;
	}
	printEnd();
}
catch (Exception $ex)
{
	Log::error($ex);
	printEnd();
}

//ignore_user_abort(true);
if(Helper::isAjax()){
	apache_setenv('no-gzip', '1');
	header("Transfer-Encoding: ");
	header("Content-type: application/javascript");
	//header("Content-Encoding: ");
}
$size = ob_get_length();
header("Content-Length: {$size}");
ob_end_flush();
flush();

Notify::mailDo();